// socket服务
// @system GO-CRAWL <shop-yun.com>
// @version go-crawl 1.0
// @author xiaotangren  <unphp@qq.com>
// @data 2014-07-29

package socket

import (
	"fmt"
	"net"
	"os"
	base "shop-yun.go/go-core/utils/base"
)

//异步并发数量
const (
	MAX_CONN_NUM = 1000
	USER         = "shop-yun"
	PASSWORD     = "123456"
)

func NewSockey(mode, host, port string, log base.Log) *Socket {
	return &Socket{
		mode: mode,
		host: host,
		port: port,
		//stoptag: stoptag,
		log: log,
	}
}

//socket结构体
type Socket struct {
	mode string //协议：tcp/udp
	host string //主机ip
	port string //端口
	//stoptag string   //发送数据的终止符
	log base.Log //系统日志
}

//开始启动socket服务
func (this *Socket) Run() {
	listener, err := net.Listen(this.mode, this.host+":"+this.port)
	if err != nil {
		this.log.Println("socket error : " + err.Error())
		os.Exit(1)
	}
	defer listener.Close()
	this.log.Println("socket running ...")
	conn_chan := make(chan net.Conn)
	//预开启子协程
	for i := 0; i < MAX_CONN_NUM; i++ {
		go func() {
			for conn := range conn_chan {
				fmt.Println("get request ... ")
				socketDoing(conn)
				fmt.Println("over request ... ")
			}
		}()
	}
	//开始监听
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accept:", err.Error())
			return
		}
		//通过信道，转交给预开启的子协程处理，达到非阻塞监听处理请求
		conn_chan <- conn
	}

}
